package Servlet.Blog.util;


import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author liyy
 * @description
 * @time 2020/10/13 21:44
 */
public class JSONUtil {
    //从输入流中 获取JSON数据
    public static JSONObject getJSON(HttpServletRequest req, HttpServletResponse res)
        throws IOException
    {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader br = req.getReader();
        while ((line = br.readLine())!=null){
            sb.append(line);
        }
        String jsonStr = sb.toString();
        JSONObject jsonObj = JSONObject.fromObject(jsonStr);
        return jsonObj;
    }

    public static void returnJSON(HttpServletRequest req,HttpServletResponse res, JSONObject jsonObj)
        throws IOException
    {
        res.setCharacterEncoding("utf-8");

        PrintWriter out = res.getWriter();
        out.write(jsonObj.toString());
        out.flush();
        out.close();
    }

}
